package me.yuzho.study.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class EvenChecker implements Runnable {
    
    private IntGenerator generator;
    
    private final int id;
    
    public EvenChecker(IntGenerator g, int id) {
        this.generator = g;
        this.id = id;
    }

    @Override
    public void run() {
        while (!generator.isCanceled()) {
            int val = generator.next();
            if(val % 2 != 0) {
                System.out.println(val + " not even!");
                generator.cancel();
            }
            
        }

    }
    
    // Test any type of IntGenerator
    public static void test(IntGenerator gp, int count) {
        System.out.println("Press control-c to exit");
        
        ExecutorService exec = Executors.newCachedThreadPool();
        
        IntStream.range(0, count).forEach(i -> {
            exec.execute(new EvenChecker(gp, i));
        });
        
        exec.shutdown();
    }
    
    //Default value for count
    public static void test(IntGenerator gp) {
        test(gp, 10);
    }

    public int getId() {
        return id;
    }

}
